import { ipcMain } from 'electron'
import * as fs from 'fs'
import { IFSResult } from '../../preload/index.d'

export function setupFsHandlers(): void {
  // 检查文件是否存在
  ipcMain.handle('fs.existsSync', async (_, path: string): Promise<IFSResult<boolean>> => {
    try {
      const exists = fs.existsSync(path)
      return {
        success: true,
        data: exists
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error)
      }
    }
  })

  // 获取产品路径
  ipcMain.handle('fs.productPath', async (): Promise<IFSResult<string>> => {
    try {
      const path = process.env.PRODUCT_PATH || ''
      return {
        success: true,
        data: path
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error)
      }
    }
  })

  // 创建目录
  ipcMain.handle('fs.mkdir', async (_, path: string): Promise<IFSResult<void>> => {
    try {
      await fs.promises.mkdir(path, { recursive: true })
      return {
        success: true
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error)
      }
    }
  })

  // 写入文件
  ipcMain.handle('fs.writeFile', async (_, path: string, data: string): Promise<IFSResult<void>> => {
    try {
      await fs.promises.writeFile(path, data, 'utf8')
      return {
        success: true
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error)
      }
    }
  })

  // 删除文件
  ipcMain.handle('fs.unlink', async (_, path: string): Promise<IFSResult<void>> => {
    try {
      await fs.promises.unlink(path)
      return {
        success: true
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error)
      }
    }
  })

  // 删除目录
  ipcMain.handle('fs.rmdir', async (_, path: string): Promise<IFSResult<void>> => {
    try {
      await fs.promises.rmdir(path)
      return {
        success: true
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error)
      }
    }
  })

  // 读取文件
  ipcMain.handle('fs.readFile', async (_, path: string): Promise<IFSResult<string>> => {
    try {
      const data = await fs.promises.readFile(path, 'utf8')
      return {
        success: true,
        data
      }
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error)
      }
    }
  })
} 